package com.bandi.tharshesnows;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Map.Entry;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bandi.tharshesnows.model.SkiTransport;
import com.bandi.tharshesnows.model.Skirun;
import com.bandi.tharshesnows.pics.PictureStorage;

public class SkirunActivity extends BaseActivity {

	private static final String MAP_URI_PATTERN = "http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q={0},{1}&sspn={0},{1}&ie=UTF8&z=16";
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"dd.MM.yyyy, HH:mm");

	private long skirunId, localityId, countyId;
	private boolean loaded;
	private Skirun skirun;
	private ImageView mapImage, tkImg, tgImg, tsf2Img, tsf4Img, canon, lights;
	private LinearLayout mainLayout;
	private TextView skirunName, skirunHeight, skirunLength, skirunState,
			skirunWidth, skirunInclintaion, skirunDifficulty, skirunDate;
	private TextView program, observatii;
	private String tkText = "Instalatii:", tgText = "Instalatii:",
			tsf2Text = "Instalatii:", tsf4Text = "Instalatii:";
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.skirun_layout);
		skirunId = getIntent().getLongExtra("SKIRUN_ID", -1);
		localityId = getIntent().getLongExtra("LOC_ID", -1);
		countyId = getIntent().getLongExtra("COUNTY_ID", -1);

		mainLayout = (LinearLayout) findViewById(R.id.skirun_details_layout);
		mainLayout.setVisibility(View.INVISIBLE);
		mapImage = (ImageView) findViewById(R.id.map_img);
		skirunName = (TextView) findViewById(R.id.skirun_name);
		skirunName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});
		skirunHeight = (TextView) findViewById(R.id.snow_height);
		skirunLength = (TextView) findViewById(R.id.skirun_length);
		skirunState = (TextView) findViewById(R.id.skirun_state);
		skirunWidth = (TextView) findViewById(R.id.skirun_width);
		skirunInclintaion = (TextView) findViewById(R.id.skirun_inclination);
		skirunDifficulty = (TextView) findViewById(R.id.skirun_difficulty);
		tkImg = (ImageView) findViewById(R.id.tk);
		tgImg = (ImageView) findViewById(R.id.tg);
		tsf2Img = (ImageView) findViewById(R.id.tsf2);
		tsf4Img = (ImageView) findViewById(R.id.tsf4);
		tkImg.setTag(false);
		tgImg.setTag(false);
		tsf2Img.setTag(false);
		tsf4Img.setTag(false);
		tkImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ((Boolean) v.getTag()) {
					showAlert("Instalatii", tkText, "Ok");
				}
			}
		});
		tgImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ((Boolean) v.getTag()) {
					showAlert("Instalatii", tgText, "Ok");
				}
			}
		});
		tsf2Img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ((Boolean) v.getTag()) {
					showAlert("Instalatii", tsf2Text, "Ok");
				}
			}
		});
		tsf4Img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ((Boolean) v.getTag()) {
					showAlert("Instalatii", tsf4Text, "Ok");
				}
			}
		});
		canon = (ImageView) findViewById(R.id.canon);
		lights = (ImageView) findViewById(R.id.lights);
		program = (TextView) findViewById(R.id.program_txt);
		observatii = (TextView) findViewById(R.id.obs_txt);
		skirunDate = (TextView) findViewById(R.id.skirun_date);
		ImageButton refreshButton = (ImageButton) findViewById(R.id.refresh_btn);
		refreshButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateData(true);
			}
		});
	}

	private void loadData() {
		if (skirun.getLocation() != null
				&& skirun.getLocation().getStaticMapImagePath() != null) {
			Bitmap bmp = PictureStorage.getInstance().getImage(
					skirun.getLocation().getStaticMapImagePath());
			if (bmp != null) {
				mapImage.setImageBitmap(bmp);
				mapImage.setVisibility(View.VISIBLE);
				mapImage.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent mapIntent = new Intent(Intent.ACTION_VIEW);
						mapIntent.setData(Uri.parse(MessageFormat.format(
								MAP_URI_PATTERN, skirun.getLocation()
										.getLatitude(), skirun.getLocation()
										.getLongitude())));
						startActivity(mapIntent);
					}
				});
			} else if (isOnline()) {
				// TODO - download map
			}
		}
		skirunName.setText(skirun.getName());
		skirunHeight.setText("" + (int) skirun.getSnowHeight());
		skirunLength.setText((int) skirun.getLength() + " M");
		skirunState.setText(skirun.getSkirunStatus().getText().toUpperCase());
		if (skirun.isOpen()) {
			skirunState.setTextColor(getResources().getColor(
					R.color.holo_blue_dark));
		} else {
			skirunState.setTextColor(Color.RED);
		}
		skirunWidth.setText((int) skirun.getWidth() + " M");
		skirunInclintaion.setText((int) skirun.getInclination() + " %");
		switch (skirun.getDifficulty()) {
		case EASY:
		case VERY_EASY:
			skirunDifficulty.setText("usuoara");
			skirunDifficulty.setTextColor(getResources().getColor(
					R.color.holo_blue_dark));
			break;
		case MEDIUM:
			skirunDifficulty.setText("medie");
			skirunDifficulty.setTextColor(Color.RED);
			break;
		case HARD:
			skirunDifficulty.setText("dificila");
			skirunDifficulty.setTextColor(Color.BLACK);
			break;
		case UNKNOWN:
			skirunDifficulty.setText("necunoscuta");
			skirunDifficulty.setTextColor(getResources().getColor(
					R.color.darker_gray));
			break;
		}
		for (Entry<SkiTransport, Integer> transports : skirun
				.getSkiTransports().entrySet()) {
			SkiTransport transport = transports.getKey();
			switch (transport) {
			case BS:
			case TK1:
			case TK2:
				tkText += "\n" + transports.getValue() + " x "
						+ transport.name() + " - " + transport.getDefinition();
				tkImg.setTag(true);
				tkImg.setBackgroundResource(R.drawable.tk);
				break;
			case TC:
			case TG:
				tgText += "\n" + transports.getValue() + " x "
						+ transport.name() + " - " + transport.getDefinition();
				tgImg.setTag(true);
				tgImg.setBackgroundResource(R.drawable.tg);
				break;
			case TSF2:
				tsf2Text += "\n" + transports.getValue() + " x "
						+ transport.name() + " - " + transport.getDefinition();
				tsf2Img.setTag(true);
				tsf2Img.setBackgroundResource(R.drawable.tsf2);
				break;
			case TSF4:
			case TSD4:
				tsf4Text += "\n" + transports.getValue() + " x "
						+ transport.name() + " - " + transport.getDefinition();
				tsf4Img.setTag(true);
				tsf4Img.setBackgroundResource(R.drawable.tsf4);
				break;
			}
		}
		if (skirun.hasCanons()) {
			canon.setBackgroundResource(R.drawable.canon);
		}
		if (skirun.isNightmode()) {
			lights.setBackgroundResource(R.drawable.lights);
		}
		program.setText(Html.fromHtml("<div style=\"display:block\">"
				+ skirun.getSchedule() + "</div>"));
		observatii.setText(Html.fromHtml(skirun.getObservations()));
		skirunDate.setText(MessageFormat.format(
				getString(R.string.last_update_txt),
				DATE_FORMAT.format(skirun.getUpdated())));
		mainLayout.setVisibility(View.VISIBLE);
	}

	private void updateData(boolean forceUpdate) {
		if (forceUpdate && !isOnline()) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					showFailedAlert("Nu exista o conexiune la internet!");
				}
			});
			return;
		}
		progressDialog = ProgressDialog.show(this, "Actualizare",
				"Actualizare partie..");
		Log.e("SNOW", "updating");
		SkirunsProvider.getInstance().getSkirun(countyId, localityId, skirunId,
				forceUpdate, new GetDataCallback<Skirun>() {

					@Override
					public void onError(Throwable t) {
						Log.e("SNOW", "failed", t);
						progressDialog.dismiss();
					}

					@Override
					public void onData(final Skirun data) {
						Log.d("SNOW", "onData");
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								loaded = true;
								skirun = data;
								loadData();
								progressDialog.dismiss();
							}
						});
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!loaded) {
			updateData(false);
		}
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
	 * menu; this adds items to the action bar if it is present.
	 * getMenuInflater().inflate(R.menu.activity_main, menu); MenuItem menuItem
	 * = menu.add("Refresh"); menuItem.setIcon(R.drawable.ic_menu_refresh); //
	 * menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
	 * menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
	 * 
	 * @Override public boolean onMenuItemClick(MenuItem item) {
	 * updateData(true); return true; } }); return true; }
	 */

}
